package com.example.uniappspringbootstartweb.controller;

import com.example.uniappspringbootstartweb.DTO.Message;
import com.example.uniappspringbootstartweb.entity.Comments;
import com.example.uniappspringbootstartweb.entity.Content;
import com.example.uniappspringbootstartweb.entity.Shares;
import com.example.uniappspringbootstartweb.entity.Userlike;
import com.example.uniappspringbootstartweb.service.CommentService;
import com.example.uniappspringbootstartweb.service.SharesService;
import com.example.uniappspringbootstartweb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Created by lilijava
 * on 2025/1/1
 * <p>
 * on  uni-app-springboot-start-web
 */
@CrossOrigin(origins = "http://localhost:8080")
@RestController
@RequestMapping("/api/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;
    @GetMapping("/total")
    public int getCommentByContentId(Integer contentId) {
        List<Comments> list=commentService.getCommentByContentid(Long.valueOf(contentId));
        int size = list.size();
        return size;
    }
    @GetMapping("/message")
    public ResponseEntity<List<Message>> getMessageByContentId(Integer contentId) {
        List<Comments> list=commentService.getCommentByContentid(Long.valueOf(contentId));
        List<Message> messages = new ArrayList<>();
        for (Comments comment : list) {
            Long  userid= comment.getUserid();
            String message = comment.getMessage();
            System.out.println(message);
            Message mess = new Message(userService.findById(userid).getUsername(), message);
            Optional<Message> optionalContent = Optional.of(mess);
            // 如果找到了内容，则添加到列表中
            optionalContent.ifPresent(messages::add);
        }
        return  ResponseEntity.ok(messages);
    }

    @GetMapping("/add")
    public int save(Integer contentId, String message) {
       Comments comments= new Comments(Long.valueOf(contentId), 1l,message);
        commentService.save(comments);
        List<Comments> list=commentService.getCommentByContentid(Long.valueOf(contentId));
        int size = list.size();
        return size;
    }
}